﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Ecommerce.Areas.Manager.Models;
using Ecommerce.Common;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;

namespace Ecommerce.Areas.Manager.Controllers
{
    [EAuthorization(LoginPage = EConst.ADMIN_LOGIN_PATH)]
    public class ProductController : Controller
    {
        private DatabaseContext db = new DatabaseContext();

        //
        // GET: /Product/

        public ActionResult Index()
        {

            List<Product> productList = db.Products.OrderBy(x => x.ProductStatus).ThenByDescending(x => x.ProductID).ToList();
            foreach (Product p in productList)
            {
                p.StatusName = Enum.GetName(typeof(EcommerceEnum.ProductStatus), p.ProductStatus);
            }

            return View(productList);
        }

        public ActionResult Regist()
        {
            // get category List
            Product p = new Product();

            p.CategoryList = db.Categories.OrderByDescending(x => x.Order).ToList();

            return View(p);
        }

        [HttpPost]
        public ActionResult Regist(Product p)
        {
            if (ModelState.IsValid)
            {

                // validate file
                HttpFileCollectionBase files = Request.Files;
                if (files.Count > 10)
                {
                    ViewBag.ErrorMsg = "Maximum count of file upload is 10";
                    return View(p);
                }
                for (int i = 0; i < files.Count; i++)
                {
                    string type = files[0].ContentType;
                    int size = files[0].ContentLength;

                    if (size > 2097152)
                    {
                        ViewBag.ErrorMsg = "Maximum size of file upload is 2Mb";
                        return View(p);
                    }
                    if (!"image/jpeg".Equals(type) && !"image/png".Equals(type) && !"image/gif".Equals(type))
                    {
                        ViewBag.ErrorMsg = "Image is incorrect";
                        return View(p);
                    }
                }

                // check exist category
                Category c = db.Categories.Find(p.CategoryId);
                if (c == null)
                {
                    return RedirectToAction("Index", p.ProductID);
                }

                // do upload file
                string prodImg = string.Empty;
                // set thum
                if (files != null && files.Count != 0)
                {
                    string fileName = "thum_" + p.CategoryId + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day
                        + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second
                        + p.ProdName + files[0].FileName;

                    Image img = Image.FromStream(files[0].InputStream);
                    Bitmap bitmap = new Bitmap(250, 140);
                    Graphics g = Graphics.FromImage(bitmap);

                    g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, bitmap.Width, bitmap.Height));
                    g.DrawImage(img, new Rectangle(0, 0, bitmap.Width, bitmap.Height));

                    string fullPath = Server.MapPath(EConst.IMAGE_PRODUCT_UPLOAD_PATH) + "\\" + fileName;

                    bitmap.Save(fullPath, ImageFormat.Jpeg);
                    g.Dispose();
                    bitmap.Dispose();
                    img.Dispose();

                    prodImg += fileName + "|";
                }

                // save all file
                for (int i = 0; i < files.Count - 1; i++)
                {
                    string fileName = p.CategoryId + DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day
                        + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second
                        + p.ProdName + files[i].FileName;

                    files[i].SaveAs(Server.MapPath(EConst.IMAGE_PRODUCT_UPLOAD_PATH) + "\\" + fileName);
                    prodImg += fileName + "|";

                }

                p.LastUpdate = DateTime.Now;
                p.Image = prodImg;

                // regist product
                db.Products.Add(p);

                // update count of products of category
                c.Products++;

                db.Entry(c).State = System.Data.EntityState.Modified;

                db.SaveChanges();

                return RedirectToAction("Detail", new { ID = p.ProductID });
            }

            // reload data screen
            p.CategoryList = db.Categories.OrderByDescending(x => x.Order).ToList();

            return View(p);
        }

        public ActionResult Edit(string id)
        {
            int productID = 0;
            try
            {
                productID = Int32.Parse(id);
            }
            catch
            {
                return RedirectToAction("Index");
            }

            Product p = db.Products.Find(productID);

            if (p == null)
            {
                return RedirectToAction("Index");
            }

            p.CategoryList = db.Categories.OrderByDescending(x => x.Order).ToList();

            return View(p);
        }

        [HttpPost]
        public ActionResult Edit(Product p)
        {
            if (ModelState.IsValid)
            {
                p.LastUpdate = DateTime.Now;
                db.Entry(p).State = System.Data.EntityState.Modified;
                db.Entry(p).Property(e => e.Image).IsModified = false;
                db.SaveChanges();
            }

            return RedirectToAction("Detail", new { ID = p.ProductID });
        }


        public ActionResult Detail(string id)
        {
            int productID = 0;
            try
            {
                productID = Int32.Parse(id);
            }
            catch
            {
                return RedirectToAction("Index");
            }

            Product p = db.Products.Find(productID);

            if (p == null)
            {
                return RedirectToAction("Index");
            }

            // get image
            if (!string.IsNullOrEmpty(p.Image))
            {
                List<string> img = p.Image.Split('|').ToList();

                img.RemoveAt(0);
                img.RemoveAt(img.Count - 1);
                ViewBag.ImgList = img;
            }
            p.StatusName = Enum.GetName(typeof(EcommerceEnum.ProductStatus), p.ProductStatus);

            return View(p);
        }

        public ActionResult Delete(string id)
        {
            // get parameter
            int productID = 0;
            try
            {
                productID = Int32.Parse(id);
            }
            catch
            {
                return RedirectToAction("Index");
            }

            // check order
            Product p = db.Products.Find(productID);

            // find image
            if (!string.IsNullOrEmpty(p.Image))
            {
                string[] imgList = p.Image.Split('|');
                foreach (string img in imgList)
                {
                    FileInfo f = new FileInfo(Server.MapPath(EConst.IMAGE_PRODUCT_UPLOAD_PATH) + img);
                    try
                    {
                        f.Delete();
                    }
                    catch { }
                }
            }

            db.Products.Remove(p);
            db.SaveChanges();

            return RedirectToAction("Index");
        }

    }
}
